const db = require("../db/mysql");
const { UUID } = require("../utils/config");

const getOrgChildrens=(oid,orgs)=>{
  //oid为父级id，根据父级id查询该组织的子集 
  const son= orgs.filter(d=>d.OParentID==oid);
  const data=[];
  son.forEach(d=>{
     //循环查找出当前组织的子集
     const children= getOrgChildrens(d.OID,orgs);
     data.push({
       id:d.OID,
       name:d.OName,
       OIcon:d.OIcon,
       children:children
     })
  })
  return data
}


/**
 *  根据每次传入id,查找id有哪些子集
 * @param {*} id  查找id的子集
 * @param {*} orgs 所有的组织
 * @returns 
 */
const  getAllChildrenIDS=(id,orgs)=>{
  let ids=[]; //用于存储所有的子集id
   //查找父级id为传入的id的组织，符合条件的就是传入id的一级子级
   const son=orgs.filter(d=>d.OParentID==id);

  //循环子集，查找子集的子集有哪些
   son.forEach(d=>{
     //将循环的当前的组织id先存入ids
     ids.push(d.OID);
     //将循环的当前的组织id在调用方法，查找当前的组织是否还有其他子集，有的话就先循环找自己的子集，没有之后在进行son的下一个组织的循环
     ids=ids.concat(getAllChildrenIDS(d.OID,orgs));
   })
   return ids
}


//根据id查找子集id 返回所有查找到的id
const getAllChildrenID=async (id)=>{
 
  const sql='select *from organization'  
  //查找所有组织
  const orgs=await db.query(sql);
  //传入id，查找id下的子集id
  console.log(id,"我是id");
  const allOrgId= await getAllChildrenIDS(id,orgs);
  //添加当前id
  allOrgId.push(id);
  return allOrgId;

}

const myOrgs={
     /**
      * 移除组织内用户 修改用户OUIsInvalid达到伪移除效果
      * @param {*} id 
      */
     removeUser:async(id)=>{
        const sql="UPDATE orgusers set OUIsInvalid=1,OUInvalidTime=NOW() where OUID=?";
        const result=await db.query(sql,id);
        if(result==null){
          return{
            code:-500,
            message:"请联系管理员"
          }
        }
        if(result.affectedRows>0){
           return{
            code:0,
            message:"操作成功"
           }
        }else{
          return{
            code:-1,
            message:"操作失败"
           }
        }


     },   
     /**
      * 根据组织查找该组织下面有哪些用户
      * @param {*} page  页码
      * @param {*} limit  每页显示数量
      * @param {*} oid 需要查找的组织的id (包括该组织的子组织的用户)
      * @param {*} key 模糊查询的条件
      * @returns 
      */
     getCurrOrgUsers:async(page,limit,oid,key)=>{
       let temp="";
       //所有要查找的组织id
        const oids=await  getAllChildrenID(oid);
        oids.forEach((d, i) => {
          temp += "\'" + d + "\'"
          if (i < (oids.length - 1)) {
              temp += ',';
          }
      });

      //查询数量
      const usersCount=`select count(*) as userCount
      from orgusers as ou 
      inner join users as u on ou.OUUID=u.uid
      inner join zhiwu as z on ou.OUZID=z.ZID 
      INNER JOIN organization as oz on ou.OUOID=oz.OID
      where (u.UName like '%${key}%' or u.UAccount like '%${key}%') and ou.OUIsInvalid=0 and ou.ouoid in (${temp}) `
    
      //执行sql根据条件查询总条数
      const result2= await db.query(usersCount);
      const total = result2[0].userCount;
      //如果没有数据直接返回
      if(total===0){
        return {
          code: 0,
          data: {
              data: [],
              total: 0
          },
      }
    }
        const sql2=`select u.uid,ou.ouid,u.uname,u.uaccount,z.ZName,oz.OName
          from orgusers as ou 
          inner join users as u on ou.OUUID=u.uid
          inner join zhiwu as z on ou.OUZID=z.ZID 
          INNER JOIN organization as oz on ou.OUOID=oz.OID
          where (u.UName like '%${key}%' or u.UAccount like '%${key}%') and ou.OUIsInvalid=0 and ou.ouoid in (${temp}) 
          limit ${(page - 1) * limit},${limit}`;
          console.log(sql2);
          const result=await db.query(sql2);
          const data = [];
          //组装表格显示需要的数据
          result.forEach(d => {
              data.push({
                  id: d.ouid,
                  uid: d.uid,
                  name: d.uname,
                  account: d.uaccount,
                  zhiwu: d.ZName,
                  oname:d.OName
              });
          });
          return  {
            message:"ok",
            data:{
              total:total,
              data:data
            },
            code:0
          }
     },
  

     //获取组织列表
     getOrganizations:async()=>{
          const sql=`select *from organization`;
          let orgs=await db.query(sql);
          let orgData=[]  

        //顶级组织  过滤条件:顶级组织没有父级
         const root= orgs.filter(d=>d.OParentID==null)
         root.forEach(d=>{
           const children= getOrgChildrens(d.OID,orgs)
           orgData.push({
              id:d.OID,
              name:d.OName,
              OIcon:d.OIcon,
              children:children
           })
         })
         return {
          message:"ok",
          data:orgData,
          code:0
        }
     },

     //获取菜单列表
    getMyMenus:async()=>{
        const sql="select *from rights where RIsBan=0 and RIsPublish=1"
        let result=await db.query(sql);
        //顶级菜单
        let parentData= result.filter(d=>d.RParentRID=="");
        const MenuData=[];

        parentData.forEach(e => {
           //经过循环，获得当前数据得子集菜单
          const temp=result.filter(d=>d.RParentRID==e.RID);
          let children=[];

          //循环子集，将需要得数据添加到children数组中
          temp.forEach(f=> {
            children.push({
                id: f.RID,
                name: f.RName,
                explain: f.RExplain,
                url:f.RUrl,
                icon: f.RIcon,
                no: f.RNo,
            })
          })


          //经过循环,将当前的菜单的数据进行组装,children是当前一级菜单的子菜单的数据 最终菜单数据
          MenuData.push({
            id: e.RID,
            name: e.RName,
            explain: e.RExplain,
            // url:children.length>0?UUID():e.url,
            url:e.RUrl==""?UUID():e.RUrl,
            icon: e.RIcon,
            no: e.RNo,
            children:children
          })


        });
    
       if(result==null){
           return{
            code: -500,
            message: '程序出现问题'
           }
       }

       return {
        code:0,
        message:"ok",
        data:MenuData
       }
    }
}

module.exports=myOrgs